// 清理可能存在的旧实例
if (typeof taskResults !== 'undefined' && taskResults.table) {
    try {
        taskResults.table.destroy();
        $('#resultTable').empty();
        console.log('✅ 旧DataTable实例清理成功');
    } catch (e) {
        console.error('❌ 清理旧DataTable实例失败:', e);
    }
}

// 结果查看
var taskResults = {
    table: null,
    detailModal: null,
    compareModal: null,
    currentTaskId: null,
    currentResults: [],

    // 初始化
    init: function() {
        console.log('初始化结果查看页面...');
        this.initModals();
        this.initTable();
        this.loadTaskList();
        this.bindEvents();
    },

    // 初始化模态框
    initModals: function() {
        this.detailModal = new bootstrap.Modal(document.getElementById('resultDetailModal'));
        this.compareModal = new bootstrap.Modal(document.getElementById('compareModal'));
    },

    // 初始化表格
    initTable: function() {
        const self = this;
        this.table = $('#resultTable').DataTable({
            processing: true,
            serverSide: false,
            data: [],
            columns: [
                { data: 'questionId' },
                { 
                    data: 'questionContent',
                    render: function(data) {
                        return data ? data.substring(0, 50) + (data.length > 50 ? '...' : '') : '-';
                    }
                },
                { 
                    data: 'platformName',
                    render: function(data) {
                        const platformMap = {
                            'deepseek': '<span class="badge bg-primary">DeepSeek</span>',
                            'yuanbao': '<span class="badge bg-success">元宝</span>',
                            'doubao': '<span class="badge bg-info">豆包</span>'
                        };
                        return platformMap[data] || data;
                    }
                },
                { 
                    data: 'answerContent',
                    render: function(data) {
                        if (!data) return '-';
                        const preview = data.substring(0, 100);
                        return preview + (data.length > 100 ? '...' : '');
                    }
                },
                { 
                    data: 'collectStatus',
                    render: function(data) {
                        const statusMap = {
                            'success': '<span class="badge bg-success">成功</span>',
                            'failed': '<span class="badge bg-danger">失败</span>',
                            'timeout': '<span class="badge bg-warning">超时</span>'
                        };
                        return statusMap[data] || data;
                    }
                },
                { 
                    data: 'collectTime',
                    render: function(data) {
                        return data ? new Date(data).toLocaleString('zh-CN') : '-';
                    }
                },
                { 
                    data: null,
                    render: function(data, type, row) {
                        return `
                            <button class="btn btn-sm btn-primary view-detail" data-id="${row.resultId}">
                                <i class="fas fa-eye"></i> 查看
                            </button>
                            <button class="btn btn-sm btn-info compare-result" 
                                    data-task-id="${row.taskId}" 
                                    data-question-id="${row.questionId}">
                                <i class="fas fa-columns"></i> 对比
                            </button>
                        `;
                    }
                }
            ],
            order: [[0, 'asc'], [2, 'asc']],
            language: {
                url: null,
                processing: "加载中...",
                search: "搜索:",
                lengthMenu: "显示 _MENU_ 条",
                info: "显示 _START_ 到 _END_ 条，共 _TOTAL_ 条",
                infoEmpty: "暂无数据",
                infoFiltered: "(从 _MAX_ 条中过滤)",
                zeroRecords: "暂无匹配数据",
                emptyTable: "暂无数据",
                paginate: {
                    first: "首页",
                    previous: "上一页",
                    next: "下一页",
                    last: "末页"
                }
            }
        });
    },

    // 加载任务列表
    loadTaskList: function() {
        taskApi.getList(1, 1000).then(res => {
            const tasks = res.data.list || [];
            const select = $('#filterTask');
            select.empty().append('<option value="">请选择任务...</option>');
            
            // 只显示有采集结果的任务
            const validTasks = tasks.filter(t => 
                t.taskStatus === 'running' || 
                t.taskStatus === 'completed' ||
                (t.successCount && t.successCount > 0)
            );
            
            validTasks.forEach(t => {
                select.append(`<option value="${t.taskId}">${t.taskName} (${t.taskStatus})</option>`);
            });
        });
    },

    // 绑定事件
    bindEvents: function() {
        const self = this;

        // 查询按钮
        $('#searchBtn').click(function() {
            self.loadResults();
        });

        // 重置按钮
        $('#resetBtn').click(function() {
            $('#filterTask').val('');
            $('#filterPlatform').val('');
            self.table.clear().draw();
        });

        // 查看详情
        $('#resultTable').on('click', '.view-detail', function() {
            const resultId = $(this).data('id');
            self.viewDetail(resultId);
        });

        // 对比结果
        $('#resultTable').on('click', '.compare-result', function() {
            const taskId = $(this).data('task-id');
            const questionId = $(this).data('question-id');
            self.compareResults(taskId, questionId);
        });

        // 导出HTML
        $('#exportHtmlBtn').click(function() {
            self.exportHtml();
        });
    },

    // 加载结果
    loadResults: function() {
        const taskId = $('#filterTask').val();
        const platform = $('#filterPlatform').val();

        if (!taskId) {
            Swal.fire('提示', '请先选择任务', 'warning');
            return;
        }

        this.currentTaskId = taskId;

        resultApi.getByTask(taskId).then(res => {
            let results = res.data || [];
            
            // 平台筛选
            if (platform) {
                results = results.filter(r => r.platformName === platform);
            }

            this.currentResults = results;
            this.table.clear().rows.add(results).draw();
            
            console.log(`加载了 ${results.length} 条结果`);
        }).catch(err => {
            console.error('加载结果失败:', err);
            Swal.fire('错误', '加载结果失败', 'error');
        });
    },

    // 查看详情
    viewDetail: function(resultId) {
        const result = this.currentResults.find(r => r.resultId === resultId);
        if (!result) {
            Swal.fire('错误', '未找到结果', 'error');
            return;
        }

        let html = `
            <div class="row mb-3">
                <div class="col-md-6">
                    <table class="table table-sm">
                        <tr><td><strong>结果ID</strong></td><td>${result.resultId}</td></tr>
                        <tr><td><strong>任务ID</strong></td><td>${result.taskId}</td></tr>
                        <tr><td><strong>问句ID</strong></td><td>${result.questionId}</td></tr>
                        <tr><td><strong>平台</strong></td><td>${result.platformName}</td></tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <table class="table table-sm">
                        <tr><td><strong>采集状态</strong></td><td>${this.getStatusBadge(result.collectStatus)}</td></tr>
                        <tr><td><strong>采集时间</strong></td><td>${new Date(result.collectTime).toLocaleString('zh-CN')}</td></tr>
                        <tr><td><strong>响应时长</strong></td><td>${result.responseTime || 0} ms</td></tr>
                        <tr><td><strong>回答长度</strong></td><td>${result.answerLength || 0} 字符</td></tr>
                    </table>
                </div>
            </div>

            <div class="mb-3">
                <h6>问句内容：</h6>
                <div class="p-3 bg-light rounded">
                    ${result.questionContent}
                </div>
            </div>

            <div class="mb-3">
                <h6>回答内容：</h6>
                <div class="p-3 bg-light rounded" style="max-height: 400px; overflow-y: auto;">
                    ${result.answerHtml || result.answerContent || '无内容'}
                </div>
            </div>
        `;

        if (result.errorMessage) {
            html += `
                <div class="mb-3">
                    <h6>错误信息：</h6>
                    <div class="alert alert-danger">
                        ${result.errorMessage}
                    </div>
                </div>
            `;
        }

        $('#resultDetailContent').html(html);
        this.detailModal.show();
    },

    // 对比结果
    compareResults: function(taskId, questionId) {
        resultApi.compare(taskId, questionId).then(res => {
            const results = res.data || [];
            
            if (results.length === 0) {
                Swal.fire('提示', '该问句暂无采集结果', 'warning');
                return;
            }

            // 获取问句内容
            const questionContent = results[0].questionContent;
            
            // ⭐ 获取平台数量，用于动态调整布局
            const platformCount = results.length;
            console.log(`✅ 对比 ${platformCount} 个平台的结果`);

            let html = `
                <div class="mb-4">
                    <h5>问句内容：</h5>
                    <div class="p-3 bg-light rounded">
                        ${questionContent}
                    </div>
                </div>

                <div class="compare-container" data-platform-count="${platformCount}">
            `;

            results.forEach(result => {
                const statusBadge = this.getStatusBadge(result.collectStatus);
                html += `
                    <div class="compare-item">
                        <h6>
                            ${this.getPlatformName(result.platformName)} ${statusBadge}
                        </h6>
                        <div class="mb-2">
                            <small class="text-muted">
                                采集时间：${new Date(result.collectTime).toLocaleString('zh-CN')}<br>
                                响应时长：${result.responseTime || 0} ms<br>
                                回答长度：${result.answerLength || 0} 字符
                            </small>
                        </div>
                        <div class="result-content">
                            ${result.answerHtml || result.answerContent || '无内容'}
                        </div>
                    </div>
                `;
            });

            html += '</div>';

            $('#compareContent').html(html);
            this.compareModal.show();
        }).catch(err => {
            console.error('对比失败:', err);
            Swal.fire('错误', '对比失败', 'error');
        });
    },

    // 导出HTML
    exportHtml: function() {
        const content = $('#compareContent').html();
        if (!content) {
            Swal.fire('提示', '暂无可导出的内容', 'warning');
            return;
        }

        const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI平台结果对比</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .compare-container {
            display: flex;
            gap: 20px;
            margin-top: 20px;
            align-items: flex-start;
        }
        .compare-item {
            flex: 1;
            min-width: 0;
            max-width: 33.333%;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 15px;
            background: white;
        }
        .compare-container[data-platform-count="2"] .compare-item {
            max-width: 50%;
        }
        .compare-container[data-platform-count="1"] .compare-item {
            max-width: 100%;
        }
        .compare-item h6 {
            border-bottom: 2px solid #0d6efd;
            padding-bottom: 10px;
            margin-bottom: 15px;
            font-size: 16px;
            font-weight: 600;
        }
        .result-content {
            max-height: 500px;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 5px;
            word-wrap: break-word;
            word-break: break-word;
        }
        .result-content img {
            max-width: 100% !important;
            height: auto !important;
            display: block;
            margin: 10px 0;
        }
        .result-content table {
            max-width: 100% !important;
            table-layout: fixed;
            word-wrap: break-word;
        }
        .result-content pre,
        .result-content code {
            max-width: 100%;
            overflow-x: auto;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        .result-content::-webkit-scrollbar {
            width: 8px;
        }
        .result-content::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        .result-content::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }
        .result-content::-webkit-scrollbar-thumb:hover {
            background: #555;
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <h2>AI平台结果对比</h2>
        <p class="text-muted">导出时间：${new Date().toLocaleString('zh-CN')}</p>
        <hr>
        ${content}
    </div>
</body>
</html>
        `;

        // 创建Blob并下载
        const blob = new Blob([html], { type: 'text/html;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `AI平台结果对比_${new Date().getTime()}.html`;
        a.click();
        URL.revokeObjectURL(url);

        Swal.fire('成功', 'HTML文件已导出', 'success');
    },

    // 获取状态徽章
    getStatusBadge: function(status) {
        const statusMap = {
            'success': '<span class="badge bg-success">成功</span>',
            'failed': '<span class="badge bg-danger">失败</span>',
            'timeout': '<span class="badge bg-warning">超时</span>'
        };
        return statusMap[status] || status;
    },

    // 获取平台名称
    getPlatformName: function(platform) {
        const nameMap = {
            'deepseek': 'DeepSeek',
            'yuanbao': '元宝',
            'doubao': '豆包'
        };
        return nameMap[platform] || platform;
    }
};

// 页面加载完成后初始化（延迟执行，确保Axios配置生效）
$(document).ready(function() {
    console.log('页面加载完成，初始化结果查看...');
    
    // 延迟300ms执行，确保config.js和api.js都已加载完成
    setTimeout(function() {
        // 重新初始化Axios配置
        if (typeof initAxiosConfig === 'function') {
            initAxiosConfig();
        }
        
        // 确认配置已设置
        console.log('Axios baseURL:', axios.defaults.baseURL);
        
        // 初始化页面
        taskResults.init();
    }, 300);
});

